#coding=utf-8

import os
import re
import argparse
from datetime import datetime

# 方案设计
# 功能需求：
#
# 批量处理指定目录下的所有.sql文件
#
# 替换文件中的特定字符串（支持正则表达式）
#
# 可选是否备份原文件
#
# 支持递归子目录搜索
#
# 技术选型：
#
# os模块处理文件路径
#
# re模块支持正则替换
#
# argparse实现命令行参数解析
#
# 完整代码实现
def replace_sql_files(filepath, old_str, new_str, backup=True, recursive=False, use_regex=False):
    try:
        # 读取文件内容
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()

        # 执行替换
        if use_regex:
            pattern = re.compile(old_str)
            new_content, count = pattern.subn(new_str, content)
        else:
            new_content = content.replace(old_str, new_str)
            count = new_content.count(new_str) - content.count(new_str)  # 估算替换次数

        # 如果有替换发生
        if count > 0:
            # 创建备份（如果需要）
            if backup:
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                backup_path = f"{filepath}.bak_{timestamp}"
                os.rename(filepath, backup_path)
                print(f"已创建备份: {backup_path}")

            # 写入新内容
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(new_content)

            print(f"处理成功: {filepath} (替换 {count} 处)")
            # processed_files += 1
            # total_replacements += count

    except Exception as e:
        print(f"处理失败: {filepath} - {str(e)}")
def batch_replace_sql_files(directory, old_str, new_str, backup=True, recursive=False, use_regex=False):
    """
    批量替换SQL文件中的字符串

    :param directory: 目标目录路径
    :param old_str: 要被替换的字符串或正则模式
    :param new_str: 替换后的字符串
    :param backup: 是否创建备份文件（默认True）
    :param recursive: 是否递归处理子目录（默认False）
    :param use_regex: 是否使用正则表达式（默认False）
    """
    # 验证目录是否存在
    if not os.path.isdir(directory):
        print(f"错误：目录 '{directory}' 不存在")
        return

    # 统计变量
    processed_files = 0
    total_replacements = 0

    # 遍历目录
    for root, _, files in os.walk(directory):
        for filename in files:
            if filename.endswith('.sql'):
                filepath = os.path.join(root, filename)

                try:
                    # 读取文件内容
                    with open(filepath, 'r', encoding='utf-8') as f:
                        content = f.read()

                    # 执行替换
                    if use_regex:
                        pattern = re.compile(old_str)
                        new_content, count = pattern.subn(new_str, content)
                    else:
                        new_content = content.replace(old_str, new_str)
                        count = new_content.count(new_str) - content.count(new_str)  # 估算替换次数

                    # 如果有替换发生
                    if count > 0:
                        # 创建备份（如果需要）
                        if backup:
                            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                            backup_path = f"{filepath}.bak_{timestamp}"
                            os.rename(filepath, backup_path)
                            print(f"已创建备份: {backup_path}")

                        # 写入新内容
                        with open(filepath, 'w', encoding='utf-8') as f:
                            f.write(new_content)

                        print(f"处理成功: {filepath} (替换 {count} 处)")
                        processed_files += 1
                        total_replacements += count

                except Exception as e:
                    print(f"处理失败: {filepath} - {str(e)}")

        # 如果不递归则只处理当前目录
        if not recursive:
            break

    # 输出统计信息
    print(f"\n处理完成！共处理 {processed_files} 个文件，总计替换 {total_replacements} 处")


if __name__ == "__main__":
    directory = r"E:\sql替换\new_energy20250626.sql"
    old_str = 'utf8mb4_0900_ai_ci'
    new_str = 'utf8mb4_general_ci'
    replace_sql_files(
        directory,
        old_str,
        new_str,
        False,
        False,
        False
    )


    # 命令行参数解析
    # parser = argparse.ArgumentParser(description="批量替换SQL文件中的字符串")
    # parser.add_argument("directory", help="包含SQL文件的目录路径")
    # parser.add_argument("old_str", help="要被替换的字符串")
    # parser.add_argument("new_str", help="替换后的字符串")
    # parser.add_argument("--no-backup", action="store_false", dest="backup",
    #                     help="不创建备份文件")
    # parser.add_argument("-r", "--recursive", action="store_true",
    #                     help="递归处理子目录")
    # parser.add_argument("--regex", action="store_true",
    #                     help="使用正则表达式匹配")
    #
    # args = parser.parse_args()
    #
    # # 执行替换
    # batch_replace_sql_files(
    #     directory=args.directory,
    #     old_str=args.old_str,
    #     new_str=args.new_str,
    #     backup=args.backup,
    #     recursive=args.recursive,
    #     use_regex=args.regex
    # )

    # directory=r"E:\sql替换\new_energy20250626.sql"
    # old_str='utf8mb4_0900_ai_ci'
    # new_str='utf8mb4_general_ci'
    # batch_replace_sql_files(
    #     directory,
    #     old_str,
    #     new_str,
    #     False,
    #     False,
    #     True
    # )